<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="refreshLoading"
      @refresh="onRefresh"
      :success-text="refreshSuccessText"
      :success-duration="1500"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >

        <article-item  v-for="(article, index) in list"
          :key="index"  :article="article"/>
        <!-- <van-cell
          v-for="(article, index) in list"
          :key="index"
          :title="article.title"
        /> -->
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item/index.vue'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [], // 数据列表
      loading: false, // 控制加载状态
      finished: false, // 控制加载结束状态
      timestamp: null, // 请求下一页数据的时间戳
      error: false, // 控制请求失败错误
      refreshLoading: false, // 控制下拉刷新
      refreshSuccessText: '刷新成功' // 下拉刷新成功提示文本
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    // 初始化页面,或滚动到页面底部时加载更多
    async onLoad () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id, // 频道ID
          timestamp: this.timestamp || Date.now() // 时间戳，请求新的推荐数据传当前的时间戳，请求历史推荐传指定的时间戳
        })
        // console.log(data);
        const { results } = data.data
        this.list.push(...results)

        // 模拟数据请求失败的情况
        // if (Math.random() > 0.5){
        //     JSON.parse("sjhjsjsjh")
        // }

        // 本次加载结束,把加载状态设置为结束
        this.loading = false
        if (results.length) {
          // 更新下一页的时间戳
          this.timestamp = data.data.pre_timestamp
        } else {
          // 加载结束
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    },

    // 下拉刷新
    async onRefresh () {
      try {
        // 请求数据
        const { data } = await getArticles({
          channel_id: this.channel.id, // 频道ID
          timestamp: Date.now() // 时间戳，请求新的推荐数据传当前的时间戳，请求历史推荐传指定的时间戳
        })
        // 将数据追加到数据列表的顶部
        const { results } = data.data
        this.list.unshift(...results)
        // 关闭下拉刷
        this.refreshLoading = false
        // 提示成功
        this.refreshSuccessText = `刷新成功,更新了${results.length}条数据`
      } catch (error) {
        this.refreshLoading = false
        this.refreshSuccessText = '刷新失败'
      }
    }
  }
}
</script>

<style scoped lang="less">
.article-list {
  height: 85vh;
  overflow-y: auto;
}
</style>
